<template>
  <div class="upload-container">
    <el-card class="upload-card">
      <template #header>
        <div class="card-header">
          <h2>上传文档</h2>
        </div>
      </template>
      
      <el-upload
        class="upload-area"
        drag
        :action="`${API_BASE_URL}/documents/`"
        :headers="uploadHeaders"
        :before-upload="beforeUpload"
        :on-success="handleUploadSuccess"
        :on-error="handleUploadError"
        multiple
      >
        <el-icon class="el-icon--upload"><upload-filled /></el-icon>
        <div class="el-upload__text">
          将文件拖到此处或 <em>点击上传</em>
        </div>
        <template #tip>
          <div class="el-upload__tip">
            支持上传 DOC, DOCX, PDF, XLS, XLSX, PPT, PPTX 等格式文件
          </div>
        </template>
      </el-upload>
    </el-card>

    <!-- 上传列表 -->
    <el-card class="upload-list" v-if="uploadedFiles.length > 0">
      <template #header>
        <div class="card-header">
          <h3>已上传文件</h3>
        </div>
      </template>
      
      <el-table :data="uploadedFiles" style="width: 100%">
        <el-table-column prop="title" label="文件名" />
        <el-table-column prop="file_type" label="类型" width="100" />
        <el-table-column prop="file_size_formatted" label="大小" width="100" />
        <el-table-column prop="upload_time" label="上传时间" width="180">
          <template #default="{ row }">
            {{ formatDate(row.upload_time) }}
          </template>
        </el-table-column>
        <el-table-column fixed="right" label="操作" width="120">
          <template #default="scope">
            <el-button link type="danger" @click="handleDelete(scope.row)">
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-card>
  </div>
</template>

<script setup>
import { ref } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { UploadFilled } from '@element-plus/icons-vue'
import axios from 'axios'

const API_BASE_URL = 'http://localhost:8000/api'
const uploadedFiles = ref([])

const uploadHeaders = {
  'Authorization': `Bearer ${localStorage.getItem('access_token')}`
}

const beforeUpload = (file) => {
  const allowedTypes = [
    'application/msword',
    'application/vnd.openxmlformats-officedocument.wordprocessingml.document',
    'application/pdf',
    'application/vnd.ms-excel',
    'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
    'application/vnd.ms-powerpoint',
    'application/vnd.openxmlformats-officedocument.presentationml.presentation',
    'text/plain'
  ]
  
  if (!allowedTypes.includes(file.type)) {
    ElMessage.error('不支持的文件类型')
    return false
  }
  
  return true
}

const handleUploadSuccess = (response) => {
  ElMessage.success('上传成功')
  fetchUploadedFiles()
}

const handleUploadError = (error) => {
  ElMessage.error('上传失败：' + (error.message || '未知错误'))
}

const fetchUploadedFiles = async () => {
  try {
    const response = await axios.get(`${API_BASE_URL}/documents/`, {
      headers: uploadHeaders
    })
    uploadedFiles.value = response.data
  } catch (error) {
    console.error('Error fetching documents:', error)
  }
}

const handleDelete = (file) => {
  ElMessageBox.confirm(
    '确定要删除这个文件吗？',
    '警告',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    }
  ).then(async () => {
    try {
      await axios.delete(`${API_BASE_URL}/documents/${file.id}/`, {
        headers: uploadHeaders
      })
      ElMessage.success('删除成功')
      fetchUploadedFiles()
    } catch (error) {
      ElMessage.error('删除失败')
    }
  }).catch(() => {})
}

const formatDate = (dateString) => {
  const date = new Date(dateString)
  return date.toLocaleString('zh-CN', {
    year: 'numeric',
    month: '2-digit',
    day: '2-digit',
    hour: '2-digit',
    minute: '2-digit'
  })
}

// 初始化时获取已上传文件列表
fetchUploadedFiles()
</script>

<style scoped>
.upload-container {
  max-width: 1200px;
  margin: 0 auto;
}

.upload-card {
  margin-bottom: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.card-header h2 {
  margin: 0;
  font-size: 18px;
  color: #303133;
}

.upload-area {
  display: flex;
  flex-direction: column;
  align-items: center;
}

.el-upload {
  width: 100%;
}

.el-upload-dragger {
  width: 100%;
  height: 200px;
}

.el-upload__tip {
  text-align: center;
  margin-top: 10px;
  color: #909399;
}

.upload-list {
  margin-top: 20px;
}
</style> 